<template>
    <div class="vote app_content">
        <!-- 中间 -->
        <div class="warp_body">
            <refresh-list v-model:freshMap="freshMap" @refresh="onRefresh" :finishedText="''" @onLoad="onLoad">
                <div class="carousel_box">
                    <carousel-card></carousel-card>
                </div>
                <!--推荐-->
                <div class="tabCon mescroll mescroll-bar">
                    <!-- 主活动 -->
                    <section class="box">
                        <div class="topheader region">
                            <div class="biaoti_ranking">
                                <van-notice-bar color="#fff" background="none" scrollable :text="activity.simpleDescribe" />
<!--                                {{ activity.simpleDescribe }}-->
                            </div>
                            <div class="vote_info">
                                <div>
                                    <span>{{ activity.projectNum }}</span>
                                    <div>新农人</div>
                                </div>
                                <div>
                                    <span>{{ activity.totalVoteNum }}</span>
                                    <div>总票数</div>
                                </div>
                                <div>
                                    <span>{{ activity.totalViewNum }}</span>
                                    <div>浏览量</div>
                                </div>
                            </div>
                            <p
                                class="titme_box flex_y_center"
                                style="color: rgb(52, 52, 52);"
                                v-if="endTime > 0"
                            >
                                <i
                                    class="Ticonfont iconH5_shouye_huodongxinxi_shijian"
                                    style="color: rgb(0, 0, 0);"
                                ></i
                                >结束倒计时
                                <van-count-down :time="endTime" format="DD 天 HH 时 mm 分 ss 秒" />
                            </p>
                            <p v-else class="titme_box flex_y_center" style="color: rgb(52, 52, 52)">
                                活动结束
                            </p>
                            <div class="icon_rb"></div>
                        </div>
                    </section>
<!--                    <div>微信登陆</div>-->
<!--                    <div>{{ accessToken }}</div>-->
                    <!-- 介绍 -->
                    <section class="box">
                        <div class="outline_box">
                            <div class="top_right"></div>
                            <div class="bottom_left"></div>
                            <div class="introducebox region">
                                <!-- <div class="time flex_row">
                                    <i
                                        class="Ticonfont iconshijian1 flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">投票开始:</span>
                                    <span class="flex_grow_1">{{ activity.beginTime }}</span>
                                </div> -->
                                <div class="time flex_row">
                                    <i
                                        class="Ticonfont iconshijian1 flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">投票截止:</span>
                                    <span class="flex_grow_1">{{ activity.endTime }}</span>
                                </div>
                                <div class="time flex_row">
                                    <i
                                        class="Ticonfont iconjinggao flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">投票规则:</span>
                                    <span class="flex_grow_1">{{ activity.rule }}</span>
                                </div>
                                <div class="time flex_y_center">
                                    <i
                                        class="Ticonfont iconH5_shouye_huodongxinxi_jieshao flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">活动介绍:</span>
                                    <!---->
                                </div>

                                <!-- <div class="shuoming_con">{{ activity.description }}</div> -->
                                <div class="shuoming_con">常州市“十佳新农人”评选活动正式开启网络投票，欢迎广大网友积极参与，选出您心中的“十佳新农人”。</div>
                                <div class="icon_rb"></div>
<!--
                                <div class="time flex_y_center">
                                    <i
                                        class="Ticonfont iconH5_shouye_huodongxinxi_jieshao flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">投票规则:</span>
                                </div>
                                <div class="shuoming_con">一个微信账号只能投一次票，一次投票至少选择5人才进行投票，最多选择不得超过10人。</div>
                                <div class="icon_rb"></div> -->
                                <!-- <div class="time flex_y_center">
                                    <i
                                        class="Ticonfont iconH5_shouye_huodongxinxi_jieshao flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">投票声明:</span>
                                </div>
                                <div class="shuoming_con">严禁任何作弊行为，系统会进行自动监测，一经发现立即取消投票资格。</div>
                                <div class="icon_rb"></div> -->

                                <!-- <div class="names">本活动最终解释权归常州市农业农村局所有。</div> -->
                                <div class="names">候选人按姓氏拼音排序，排名不分先后。</div>
                                <div class="names">（点击照片或姓名可查看详细介绍）</div>
                                <!-- <div class="time flex_row">
                                    <i
                                        class="Ticonfont iconjinggao flex_grow_0"
                                        style="color: rgb(0, 0, 0);"
                                    ></i>
                                    <span class="flex_grow_0">温馨提示:</span>
                                    <span class="flex_grow_1">候选人按姓氏拼音排序，排名不分先后。</span>
                                </div> -->
                            </div>
                        </div>
                    </section>

                    <!--列表-->
                    <section class="box">
                        <div class="player_box">
                            <van-checkbox-group v-model="checkedResult" max="10">
                                <van-row gutter="10">
                                    <van-col
                                        span="8"
                                        v-for="item in result.list"
                                        :key="item.subjectId"
                                    >
                                        <div
                                            class="player_list grid-item item"
                                            style="color: rgb(51, 51, 51)"
                                        >
                                            <p class="xuanshou_num">
                                                <i
                                                    class="Ticonfont iconH5_shouye_xuanshou_tupian_jiaobiao"
                                                    style="color: #04bbe0;"
                                                ></i
                                                >{{ item.subjectNo }}号
                                            </p>
                                            <div @click="handleToDetail(item.subjectId)" class="cover-box">
                                                <img class="img"
                                                    :src="item.subjectImgLink"
                                                />
                                            </div>
                                            <div @click="handleToDetail(item.subjectId)" class="xuanshou_name break1">
                                                {{ item.subjectName }}:{{ item.subjectSummay }}
                                            </div>
                                            <!-- <div class="toupiao_btn" @click="handleToDetail(item.subjectId)">详情</div> -->
                                            <van-checkbox class="toupiao_checkbox" :name="item.subjectId" shape="square"><span style="color: rgb(0, 0, 0); font-weight: bold;">{{ item.voteNumber }}</span> 票</van-checkbox>
                                        </div></van-col
                                    >
                                </van-row>
                            </van-checkbox-group>
                        </div>
                    </section>
<!--                    <van-sticky :offset-bottom="50" position="bottom">-->
<!--                        <van-button type="primary">吸底距离</van-button>-->
<!--                    </van-sticky>-->
                    <div @click="handleSubmitVote" class="box">
                        <div class="toupiaocheer">
                            <!-- <img src="~@/assets/img/icon-toupiao.png" alt=""> -->
                            投票</div>
                    </div>
                </div>
            </refresh-list>
        </div>

        <!-- 底部 -->
        <div class="footer_body">
            <footer-nav></footer-nav>
        </div>
    </div>
</template>

<script setup name="vote">
const router = useRouter();
import { parse, stringify } from 'qs'
import { showNotify, showDialog } from "vant";
const { useHome, useCommon } = $globalStore;
import vueWechatAuth from '@/plugins/vueWechatAuth';
import dayjs from "dayjs";

let freshMap = reactive({
    refreshLoad: false, // 是否刷新
    listLoading: false, // 是否加载中
    listFinished: false, // 是否加载完成标识
});
// 请求结果
const result = reactive({
    activity: {},
    list: [],
})
// 勾选项
const checkedResult = ref([]);
const activity = ref({});
// 获取
const getActivity = async () => {
    const res = await useHome.getActivity();
    if(res.success) {
        result.activity = res.body;
        activity.value = res.body;
    }
}
getActivity();

// 取列表
const getListSubject = async () => {
    const res =await useHome.getListSubject({ type: 0 });
    if(res.success) {
        result.list = res.body;
        await useHome.addView({ id: 0});
    }
    freshMap.listLoading = false;
    freshMap.listFinished = res.listFinished;
    freshMap.listFinished = true;
}
// getListSubject();

/**
 * 处理url链接
 */
 const processUrl = () => {
    const url = window.location.href
    // 解决多次登录url添加重复的code与state问题
    const params = parse(url.split('?')[1])
    let redirectUrl = url
    if (params.code && params.state) {
        delete params.code
        delete params.state
        const query = stringify(params)
        if (query.length) {
            redirectUrl = `${url.split('?')[0]}?${query}`
        } else {
            redirectUrl = `${url.split('?')[0]}`
        }
    }
    return redirectUrl
}

// 投票
const handleSubmitVote = async () => {
    if (isWeiXin() && !accessToken.value) {
        vueWechatAuth.redirectUri = processUrl()
        window.location.href = vueWechatAuth.authUrl
    } else {
        if(checkedResult.value.length < 5) {
            showDialog({ message: '至少选择5人进行投票' });
            // showNotify({ type: 'warning', message: '至少选择5人进行投票' });
            return;
        }
        const res = await useHome.submitVote({
            openId: accessToken.value,
            subjectId: checkedResult.value.map(v => parseInt(v))
        });
        if(res.success) {
            // showNotify({ type: 'success', message: '投票成功' });
            showDialog({ message: '投票成功' });
            onRefresh();
        } else {
            // showNotify({ type: 'danger', message: res.message || '投票失败' });
            showDialog({message: res.message || '投票失败' });
        }
    }
}

const handleToDetail = (id) => {
    router.push({
        name: "Details",
        query: { id },
    });
}


/**
 * 处理登录
 * @param code
 */
const processLogin = async (code) => {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await $globalStore.useCommon.getLogin({
                code,
                appid: 'wx5a3559998d4db683',
                secret: '98f6b03999ed237259004398075fbd9e',
            });
            if (res?.code === '200') {
                resolve({ status: 1, data: '登录成功' })
                // $globalStore.useCommon.SET_LOGIN_STATUS(2);
                $globalStore.useCommon.SET_ACCESS_TOKEN(res.body);
                $globalStore.useCommon.SET_WX_CODE(code);
                debugger;
            } else {
                showNotify({ type: 'warning', message: '登陆异常' });
                console.log('登陆异常:', res?.message)
                $globalStore.useCommon.SET_WX_CODE(null);
            }
            removeParam();
        } catch (err) {
            reject(err)
        }
    })
}


const isWeiXin = () => {
    const ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger";
}

const endTime = computed(function () {
    const { endTime } = activity.value;
    if (!endTime) {
        return null;
    }
    // const end = +new Date(endTime);
    // return end - (+new Date());
    const end = dayjs(endTime).valueOf();
    return end - dayjs().valueOf();
});

//下拉刷新
const onRefresh = () => {
    freshMap.listFinished = false;
    freshMap.listLoading = true;
    freshMap.refreshLoad = true;
    Promise.all([ getActivity(), getListSubject()]).then(() => {
        freshMap.refreshLoad = false;
    });
};

// 触底加载
const onLoad = () => {
    getListSubject(true);
};

const accessToken = computed(() => {
    return useCommon.accessToken;
});
const oldWxCode = computed(() => {
    return useCommon.wxCode;
});


const getQuery =  dataName => {
    function getUrlVars() {
        let vars = [],
            hash;
        let hashes = window.location.href
            .slice(window.location.href.indexOf("?") + 1)
            .split("&");
        for (let i = 0; i < hashes.length; i++) {
            hash = hashes[i].split("=");
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    let params = getUrlVars();
    for (let i = 0; i < params.length; i++) {
        if (params[i] == dataName) {
            return decodeURI(params[params[i]]);
        }
    }
    return "";
};
//获取code
// let { code } = router?.currentRoute?.value?.query;
const code = getQuery('code');
//检测本地是否存在过期code
if(oldWxCode.value && oldWxCode.value == code){
    removeParam()
} else if(code) {
   processLogin(code)
}


function removeParam() {
    window.history.pushState({}, '', '/survey/#/vote');
    // // 假设我们当前在路径 '/' 并带有参数
    // // const currentPath = router.currentRoute.value.path;
    // // const currentQuery = router.currentRoute.value.query;
    //
    // // 移除参数
    // // delete currentQuery.param;
    // // 导航到没有参数的路径
    // router.push({ path: currentPath });
}
const getTicket = async () => {
    const res = await useCommon.getTicket();
    if(res.success) {
        useCommon.SET_WX_TICKET(res.body || "");
        setWxConfig(res.body);
    }
}
const wxTicket = computed(() => {
    return useCommon.wxTicket;
});


function setWxConfig(d) {
    const {
        timestamp, nonceStr, signature
    } = d;
    wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: 'wx5a3559998d4db683', // 必填，公众号的唯一标识
        timestamp, // 必填，生成签名的时间戳
        nonceStr, // 必填，生成签名的随机串
        signature,// 必填，签名
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填，需要使用的JS接口列表
    });
    handleSetShared();
}

function handleSetShared() {
    const conf = {
        title: '常州市“十佳新农人”评选活动正式开启网络投票', // 分享标题
        link: 'https://surveys.nuyuku.cn/survey/', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'https://surveys.nuyuku.cn/survey/jpg/7-cukvAOgr.jpg', // 分享图标
    }
    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
        wx.updateAppMessageShareData({
            ...conf,
            desc: '欢迎广大网友积极参与，选出您心中的“十佳新农人', // 分享描述
            success: function () {
                // 设置成功
            }
        });
        wx.updateTimelineShareData({
           ...conf,
            success: function () {
                // 设置成功
            }
        });
    });
}

onMounted(() => {
    // if(wxTicket.value.ticket) {
    //     setWxConfig(wxTicket.value);
    // } else {
    //     // getTicket();
    // }
});
</script>

<style lang="less" scoped>
.vote {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    background-color: #f4f4f4;

    .warp_body {
        .carousel_box {
            // height: 150px;
            width: 100%;
            // padding-bottom: 10px;
        }
    }

    .boutique_box {
        .boutique_body {
            padding: 0px 0px 10px 0px;
        }
    }

    //.recommend_box {
    //    .recommend_body {
    //        width: 100%;
    //    }
    //}
}


.titme_box {
    height: 40px;
    background: #FFFFFF;
    opacity: 1;
    //border-radius: 8px;
    //margin-top: -6px;
    line-height: 30px;
    //font-size: 14px;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin: 0;
}
.box{

}
.toupiaocheer {
    position: fixed;
    bottom: 150px;
    right: 40px;
    z-index: 11;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: -webkit-linear-gradient(left, rgb(4, 187, 224), rgb(33, 236, 179));
}
.names{
    font-size: 14px;
    font-weight: bold;
    color: #000;
    text-align: center;
    // padding: 10px 0;

}
.xuanshou_name {
    height: 1rem;
    font-size: 0.28rem;
}
.xuanshou_name:hover{
    color: blue;
}
.biaoti_ranking .van-notice-bar {
    font-size: 0.36rem;
}
.toupiao_checkbox {
    font-size: 0.28rem;
}
// .cover-box{
//     background: #000;
// }
 .cover-box .img{
     max-height: 4.1rem;
         //width: 40%;
     //margin:  0 auto;
 }
 .player_box .van-row {
     flex-shrink: 0;
 }
</style>
